package com.cxf.windex.biz;

import com.cxf.windex.base.biz.BaseBiz;
import com.cxf.windex.base.common.ServiceException;
import com.cxf.windex.base.constant.UserConstant;
import com.cxf.windex.base.util.DateUtil;
import com.cxf.windex.base.util.IdUtil;
import com.cxf.windex.entity.BConfig;
import com.cxf.windex.entity.BOrders;
import com.cxf.windex.entity.BOrdersTask;
import com.cxf.windex.entity.BResouces;
import com.cxf.windex.entity.BShop;
import com.cxf.windex.entity.Money;
import com.cxf.windex.entity.vo.ResourcesPay;
import com.cxf.windex.enums.OrderTypeEnum;
import com.cxf.windex.enums.ReviewEnum;
import com.cxf.windex.mapper.BOrdersTaskMapper;
import com.cxf.windex.task.BonusTask;
import com.github.pagehelper.PageHelper;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

/**
 * @program: business_needs
 * @description: 订单任务
 * @author: chenxf
 * @create: 2018-10-17 15:47
 **/
@Service
public class BOrdersTaskBiz extends BaseBiz<BOrdersTaskMapper,BOrdersTask> {

  @Autowired
  private BResourcesBiz resourcesBiz;
  @Autowired
  private BShopBiz shopBiz;
  @Autowired
  private BonusTask bonusTask;
  @Autowired
  private BConfigBiz configBiz;

  /**
   * 查询订单任务列表
   * @param limit 数量
   * @param offset 页码
   * @param orderStr  排序(升序或者降序)
   * @param resourcesName 资源名称
   * @param resourcesId 资源ID
   * @param status 状态
   * @param reviewStatus 审核状态
   * @param type 广告类型
   * @return
   */
  public List<BOrdersTask> list(int limit, int offset,  String orderStr,String resourcesName,String  resourcesId,String status,String reviewStatus,String type) {
    Example example = new Example(BOrdersTask.class);
    Example.Criteria criteria = example.createCriteria();
    if(StringUtils.isNotBlank(resourcesId)){
      criteria.andEqualTo("resourcesId",resourcesId);
    }
    if(StringUtils.isNotBlank(type)){
      criteria.andEqualTo("type",type);
    }
    if(StringUtils.isNotBlank(resourcesName)){
      criteria.andLike("resourcesName","%"+resourcesName+"%");
    }
    if(StringUtils.isNotBlank(status)){
      if("-1".equals(status)){
        status="0";
        //未开始
        criteria.andGreaterThan("bTime",new Date());
      }else {
        criteria.andLessThan("bTime",new Date());
      }
      criteria.andEqualTo("status",status);
    }

    if(StringUtils.isNotBlank(reviewStatus)){
      criteria.andEqualTo("reviewStatus",status);
    }
    example.setOrderByClause(" b_time asc,upd_time "+orderStr );
    PageHelper.startPage(offset, limit);
    return selectByExample(example);
  }

  public List<BOrdersTask> reviewList(int limit, int offset,  String orderStr,String  resourcesId,String orderId) {
    Example example = new Example(BOrdersTask.class);
    Example.Criteria criteria = example.createCriteria();
    if(StringUtils.isNotBlank(resourcesId)){
      criteria.andEqualTo("resourcesId",resourcesId);
    }
    if(StringUtils.isNotBlank(orderId)){
      criteria.andEqualTo("orderId",orderId);
    }
    criteria.andEqualTo("status",1);

    example.setOrderByClause(" b_time asc,upd_time "+orderStr );
    PageHelper.startPage(offset, limit);
    return selectByExample(example);
  }

  /**
   * 根据IDS获取资源订单任务列表
   * @param ids 资源IDS逗号分隔
   * @param  orderId 订单ID
   * @return
   */
  public List<BOrdersTask> idsList(String  orderId,String ids) {
    Example example = new Example(BOrdersTask.class);
    Example.Criteria criteria = example.createCriteria();
    if(StringUtils.isNotBlank(orderId)){
      criteria.andEqualTo("orderId",orderId);
    }
    if (StringUtils.isNotBlank(ids)) {
      Iterable<String> idsIterables = Arrays.asList(ids.split(","));
      criteria.andIn("resourcesId",idsIterables);
    }
    example.setOrderByClause("crt_time asc" );
    return selectByExample(example);
  }

  /**
   * 保存订单任务
   * @param entity 订单任务信息
   */
  public void save(BOrdersTask entity){
    if(entity.getId()==null|| entity.getId()==0){
      throw  new ServiceException("任务异常:请填写任务ID");
    }else{
      if(entity.getStatus().equals(OrderTypeEnum.CLOSED.getKey())){
        // 发放奖励
        bonusTask.doBonus(entity.getId());
        entity.setReviewTime(new Date());
      }
      if(entity.getReviewStatus().equals(ReviewEnum.REVIEWFAIL.getKey())){
        //审核未通过  设置审核时间
        entity.setReviewTime(new Date());
      }
      updateSelectiveById(entity);

    }
  }

  public List<ResourcesPay> queryTaskMoney(String orderId,String resourcesIds){
    return mapper.queryTaskMoney(orderId,resourcesIds.split(","));
  }
  /**
   * 保存订单任务
   * @param orders 订单信息
   */
  public void saveTasks(BOrders orders){
    LocalDate localDate;
    BShop bShop=shopBiz.selectById(orders.getShopId());
    for(String id:orders.getResourcesIds().split(",")){
      if(StringUtils.isBlank(id)){
        continue;
      }
      BResouces bResouces=resourcesBiz.selectById(Long.valueOf(id));
      localDate=DateUtil.getLocalDateByDate(orders.getBTime());
      for(int i=0;i<orders.getDays().intValue();i++){
        insertSelective(new BOrdersTask().initByOrders(orders,Long.valueOf(id),localDate,bResouces,bShop));
        localDate=localDate.plusDays(1);
      }
    }
  }

  public void saveAdminTasks(BOrders orders){
    BConfig config=configBiz.getInfo(UserConstant.CONFIG_ADMIN);
    LocalDate localDate;
    String[] resourcesIds=orders.getResourcesIds().split(",");
    BigDecimal price=orders.getTotalPrice().divide(BigDecimal.valueOf(orders.getDays()),2, BigDecimal.ROUND_HALF_UP).divide(BigDecimal.valueOf(resourcesIds.length),2, BigDecimal.ROUND_HALF_UP);
   BigDecimal realPrice=BigDecimal.ZERO;
    if("0".equals(orders.getType())){
      realPrice= price.multiply(config.getLF()).divide(BigDecimal.valueOf(100));
    }else {
      realPrice=price.multiply(config.getVF()).divide(BigDecimal.valueOf(100));
    }
    for(String id:resourcesIds){
      if(StringUtils.isBlank(id)){
        continue;
      }
      BResouces bResouces=resourcesBiz.selectById(Long.valueOf(id));
      localDate=DateUtil.getLocalDateByDate(orders.getBTime());
      for(int i=0;i<orders.getDays().intValue();i++){
        insertSelective(new BOrdersTask().initAdminOrders(orders,Long.valueOf(id),localDate,bResouces,price,realPrice));
        localDate=localDate.plusDays(1);
      }
    }
  }

  public Future<String> unDone(){
    //设置未做的任务 未完成
    mapper.updateUndo(new Date());
    //设置审核中超过1天的失败
    mapper.updateReview(DateUtil.getByLocalDate(LocalDate.now()));
    return new AsyncResult<>(UserConstant.TASK_FINISHED);
  }
}
